package com.term.domain.common;

import javax.persistence.Query;

/**
 * Created by chenGang on 2017/1/5.
 */
public class Condition {

    /**
     * 字段名
     */
    protected String field;

    /**
     * 属性值
     */
    protected Object value;

    /**
     * 字段名和属性值的匹配类型
     */
    protected MatchType matchType;

    public Condition() {
    }

    public Condition(String field, Object value) {
        this(field, value, MatchType.eq);
    }

    public Condition(String field, Object value, Condition.MatchType matchType) {
        this.field = field;
        this.value = value;
        this.matchType = matchType;
    }


    public enum MatchType {
        eq("="),                // filed = value
        greater(">"),           // filed > value
        greaterOrEqual(">="),   // field >= value
        less("<"),              // field < value
        lessOrEqual("<="),      // field <= value
        notEq("!="),            // field != value
        like("like"),           // field like value
        notLike("not like"),    // field not like value
        isNull("is null");      // field is null

        MatchType(){}

        MatchType(String sqlStr) {
            this.sqlStr = sqlStr;
        }

        private String sqlStr;

        public String getSqlStr() {
            return sqlStr;
        }
    }

    public int setParameter(Query query, int paramIdx) {
        query.setParameter(paramIdx, matchType.equals(MatchType.like) ? "%" + value + "%" : value);
//        System.out.println(paramIdx + ":" + value);
        return paramIdx + 1;
    }

    public boolean isEmpty() {
        return false;
    }

    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

    public MatchType getMatchType() {
        return matchType;
    }


    @Override
    public String toString() {
        String innerField = field;

        if (matchType.equals(matchType.like))
            return innerField + " " + matchType.getSqlStr() + " ?";
        else if (matchType.equals(matchType.isNull))
            return innerField + " " + matchType.getSqlStr();
        else
            return innerField + " " + matchType.getSqlStr() + " ?";
    }
}
